package scriptTool;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities.EscapeMode;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.swing.Java2DRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * html 代码直接转图片（img）
 *
 * 需要的依赖
 *        <dependency>
 *             <groupId>org.jsoup</groupId>
 *             <artifactId>jsoup</artifactId>
 *             <version>1.15.4</version>
 *         </dependency>
 *         <dependency>
 *             <groupId>org.xhtmlrenderer</groupId>
 *             <artifactId>flying-saucer-core</artifactId>
 *             <version>9.1.22</version>
 *         </dependency>
 *         <dependency>
 *             <groupId>com.lowagie</groupId>
 *             <artifactId>itext</artifactId>
 *             <version>2.1.7</version>
 *         </dependency>
 *
 */
public class HtmlChangeIMG {

    public static void main(String[] args) {
        String htmlInputFilePath = "src/main/java/scriptTool/index.html";
        String imgOutputPath = "src/main/java/scriptTool/index.png";
        String fontPath = "src/main/java/scriptTool/Regular.ttf";

        File tempFile = null;
        try {
            // 检查输入文件
            File inputHtml = new File(htmlInputFilePath);
            if (!inputHtml.exists()) {
                throw new IOException("HTML文件不存在: " + htmlInputFilePath);
            }

            // 检查字体文件
            File fontFile = new File(fontPath);
            if (!fontFile.exists()) {
                System.out.println("警告：字体文件不存在: " + fontPath);
            }

            // 读取并处理HTML
            Document doc = Jsoup.parse(inputHtml, StandardCharsets.UTF_8.name());
            
            // 修复HTML标签以符合XHTML规范
            fixHtmlTags(doc);
            
            // 确保HTML有完整的结构，使用XHTML格式
            StringBuilder htmlContent = new StringBuilder();
            htmlContent.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
                      .append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" ")
                      .append("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n")
                      .append("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n")
                      .append("<head>\n")
                      .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n");

            // 添加自定义字体
            if (fontFile.exists()) {
                htmlContent.append("<style type=\"text/css\">\n")
                          .append("@font-face {\n")
                          .append("    font-family: 'CustomFont';\n")
                          .append("    src: url('").append(fontFile.toURI().toString()).append("') format('truetype');\n")
                          .append("}\n")
                          .append("body {\n")
                          .append("    font-family: 'CustomFont', sans-serif;\n")
                          .append("}\n")
                          .append("</style>\n");
            }
            
            // 设置文档的输出模式为XHTML
            doc.outputSettings()
               .syntax(Document.OutputSettings.Syntax.xml)
               .escapeMode(EscapeMode.xhtml);
            
            htmlContent.append("</head>\n")
                      .append("<body>\n")
                      .append(doc.body().html())
                      .append("\n</body>\n")
                      .append("</html>");
            
            // 创建临时文件
            tempFile = File.createTempFile("temp", ".xhtml");
            Files.write(tempFile.toPath(), htmlContent.toString().getBytes(StandardCharsets.UTF_8));

            // 打印生成的XHTML内容用于调试
            System.out.println("Generated XHTML content:");
            System.out.println(htmlContent.toString());

            // 确保输出目录存在
            File outputFile = new File(imgOutputPath);
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            // 渲染图片
            Java2DRenderer renderer = new Java2DRenderer(tempFile, 1024);
            Image image = renderer.getImage();
            
            // 将Image转换为BufferedImage
            BufferedImage bufferedImage;
            if (image instanceof BufferedImage) {
                bufferedImage = (BufferedImage) image;
            } else {
                bufferedImage = new BufferedImage(
                    image.getWidth(null),
                    image.getHeight(null),
                    BufferedImage.TYPE_INT_ARGB
                );
                
                Graphics2D g2d = bufferedImage.createGraphics();
                g2d.drawImage(image, 0, 0, null);
                g2d.dispose();
            }
            
            // 保存图片
            if (!ImageIO.write(bufferedImage, "PNG", outputFile)) {
                throw new IOException("无法保存为PNG格式");
            }
            
            System.out.println("HTML已成功转换为图片：" + imgOutputPath);

        } catch (IOException e) {
            System.err.println("文件操作错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("转换过程中发生错误：" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (tempFile != null && tempFile.exists()) {
                boolean deleted = tempFile.delete();
                if (!deleted) {
                    System.err.println("警告：临时文件删除失败: " + tempFile.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 修复HTML标签以符合XHTML规范
     */
    private static void fixHtmlTags(Document doc) {
        // 修复img标签
        Elements imgs = doc.getElementsByTag("img");
        for (Element img : imgs) {
            if (!img.hasAttr("alt")) {
                img.attr("alt", ""); // XHTML要求img标签必须有alt属性
            }
        }

        // 修复其他自闭合标签
        fixSelfClosingTags(doc, "br");
        fixSelfClosingTags(doc, "hr");
        fixSelfClosingTags(doc, "input");
        fixSelfClosingTags(doc, "meta");
        fixSelfClosingTags(doc, "link");

        // 确保所有标签都正确闭合
        doc.outputSettings()
           .syntax(Document.OutputSettings.Syntax.xml)
           .escapeMode(EscapeMode.xhtml);
    }

    /**
     * 修复自闭合标签
     */
    private static void fixSelfClosingTags(Document doc, String tagName) {
        Elements elements = doc.getElementsByTag(tagName);
        for (Element element : elements) {
            element.html(""); // 确保标签正确闭合
        }
    }
}
